import config from '@/config';
import { getCampusCenter, getLocationList } from '@/api/location';
import QQMapWX from '@/utils/qqmap-wx-jssdk.js';

const LOCATION_CACHE_KEY = 'selectedLocation';
const REAL_LOCATION_CACHE_KEY = 'realLocation';
const CAMPUS_CENTER_CACHE_KEY = 'campusCenter';

// 腾讯地图SDK实例
let qqmapsdk;

try {
  // 初始化腾讯地图SDK
  if (QQMapWX && config.qqMapKey) {
    qqmapsdk = new QQMapWX({
      key: config.qqMapKey
    });
    console.log('腾讯地图SDK初始化成功');
  } else {
    console.warn('腾讯地图SDK初始化失败: 缺少QQMapWX类或API密钥');
  }
} catch (error) {
  console.error('腾讯地图SDK加载失败:', error);
  qqmapsdk = null;
}

// 校园地理围栏配置（动态从后端获取）
let CAMPUS_BOUNDARY = null;

// 获取校园地理围栏配置
const getCampusBoundary = async () => {
  try {
    // 先尝试从缓存获取
    const cachedCenter = uni.getStorageSync(CAMPUS_CENTER_CACHE_KEY);
    if (cachedCenter && cachedCenter.timestamp && (Date.now() - cachedCenter.timestamp) < 3600000) { // 1小时缓存
      CAMPUS_BOUNDARY = {
        centerLat: parseFloat(cachedCenter.latitude),
        centerLng: parseFloat(cachedCenter.longitude),
        radius: cachedCenter.radius || 2000
      };
      return CAMPUS_BOUNDARY;
    }

    // 从后端获取校园中心位置
    const { data } = await getCampusCenter();
    if (data) {
      CAMPUS_BOUNDARY = {
        centerLat: parseFloat(data.latitude),
        centerLng: parseFloat(data.longitude),
        radius: data.radius || 2000
      };
      
      // 缓存校园中心配置
      uni.setStorageSync(CAMPUS_CENTER_CACHE_KEY, {
        latitude: data.latitude,
        longitude: data.longitude,
        radius: data.radius,
        timestamp: Date.now()
      });
      
      console.log('校园地理围栏配置已更新:', CAMPUS_BOUNDARY);
    } else {
      throw new Error('获取校园中心位置失败');
    }
  } catch (error) {
    console.error('获取校园地理围栏配置失败，使用默认配置:', error);
    // 使用默认配置
    CAMPUS_BOUNDARY = {
      centerLat: 39.9042,
      centerLng: 116.4074,
      radius: 2000
    };
  }
  
  return CAMPUS_BOUNDARY;
};

// 计算两点间距离（米）
const calculateDistance = (lat1, lng1, lat2, lng2) => {
  const R = 6371000; // 地球半径（米）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLng = (lng2 - lng1) * Math.PI / 180;
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLng / 2) * Math.sin(dLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
};

// 检查是否在校园范围内
const isInCampus = async (latitude, longitude) => {
  try {
    // 确保获取到校园地理围栏配置
    const boundary = await getCampusBoundary();
    
    const distance = calculateDistance(
      latitude, longitude,
      boundary.centerLat, boundary.centerLng
    );
    return distance <= boundary.radius;
  } catch (error) {
    console.error('检查校园范围失败:', error);
    // 发生错误时，默认认为在校园内，避免阻塞用户操作
    return true;
  }
};

// 获取实时定位
export const getRealTimeLocation = () => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'gcj02', // 使用国测局坐标系
      success: (res) => {
        const location = {
          latitude: res.latitude,
          longitude: res.longitude,
          accuracy: res.accuracy,
          timestamp: Date.now()
        };
        
        // 缓存实时位置
        uni.setStorageSync(REAL_LOCATION_CACHE_KEY, location);
        resolve(location);
      },
      fail: (error) => {
        console.error('获取定位失败:', error);
        reject(error);
      }
    });
  });
};

// 逆地理编码获取地址描述
export const getLocationAddress = (latitude, longitude) => {
  return new Promise((resolve, reject) => {
    // 检查SDK是否成功加载
    if (!qqmapsdk) {
      console.warn('腾讯地图SDK未加载，返回默认位置');
      resolve('当前位置');
      return;
    }

    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: (res) => {
        try {
          const result = res.result;
          let address = '';
          
          // 优先使用推荐地址
          if (result.formatted_addresses && result.formatted_addresses.recommend) {
            address = result.formatted_addresses.recommend;
          } 
          // 其次使用完整地址
          else if (result.address) {
            address = result.address;
          }
          // 最后拼接地址组件
          else if (result.address_component) {
            const component = result.address_component;
            address = `${component.province || ''}${component.city || ''}${component.district || ''}${component.street || ''}${component.street_number || ''}`;
          }
          
          // 如果地址为空，使用默认值
          if (!address || address.trim() === '') {
            address = '当前位置';
          }
          
          console.log('腾讯地图逆地理编码成功:', address);
          resolve(address);
        } catch (error) {
          console.error('解析地址信息失败:', error);
          resolve('当前位置');
        }
      },
      fail: (error) => {
        console.error('腾讯地图逆地理编码失败:', error);
        // 逆地理编码失败时，直接返回默认位置
        resolve('当前位置');
      }
    });
  });
};

// 获取当前位置（优先实时定位）
export const getCurrentLocation = async (forceRealTime = false) => {
  try {
    // 如果强制实时定位或没有缓存的实时位置，则获取实时定位
    const cachedRealLocation = uni.getStorageSync(REAL_LOCATION_CACHE_KEY);
    const now = Date.now();
    const locationExpired = !cachedRealLocation || (now - cachedRealLocation.timestamp) > 300000; // 5分钟过期
    
    if (forceRealTime || locationExpired) {
      const realLocation = await getRealTimeLocation();
      const address = await getLocationAddress(realLocation.latitude, realLocation.longitude);
      
      const locationData = {
        id: 'real_location',
        name: address,
        latitude: realLocation.latitude,
        longitude: realLocation.longitude,
        isRealTime: true
      };
      
      // 缓存当前选择的位置
      uni.setStorageSync(LOCATION_CACHE_KEY, locationData);
      return locationData;
    }
    
    // 使用缓存的实时位置
    if (cachedRealLocation) {
      const cachedLocation = uni.getStorageSync(LOCATION_CACHE_KEY);
      if (cachedLocation && cachedLocation.isRealTime) {
        return cachedLocation;
      }
      
      const address = await getLocationAddress(cachedRealLocation.latitude, cachedRealLocation.longitude);
      const locationData = {
        id: 'real_location',
        name: address,
        latitude: cachedRealLocation.latitude,
        longitude: cachedRealLocation.longitude,
        isRealTime: true
      };
      
      uni.setStorageSync(LOCATION_CACHE_KEY, locationData);
      return locationData;
    }
    
    // 如果实时定位失败，回退到预设位置列表
    return await getFallbackLocation();
    
  } catch (error) {
    console.error('获取当前位置失败:', error);
    // 如果是强制实时定位，直接抛出错误，不回退到默认位置
    if (forceRealTime) {
      throw error;
    }
    // 非强制实时定位时才回退到预设位置
    return await getFallbackLocation();
  }
};

// 回退到预设位置列表
const getFallbackLocation = async () => {
  try {
    const { data: locations } = await getLocationList();
    if (!locations || locations.length === 0) {
      throw new Error('获取位置列表失败');
    }
    
    const defaultLocation = locations[0];
    uni.setStorageSync(LOCATION_CACHE_KEY, defaultLocation);
    return defaultLocation;
  } catch (error) {
    // 如果连预设位置都获取失败，返回默认位置
    try {
      // 获取校园中心配置作为默认位置
      const boundary = await getCampusBoundary();
      const defaultLocation = {
        id: 'default',
        name: '校园内',
        latitude: boundary.centerLat,
        longitude: boundary.centerLng,
        isRealTime: false
      };
      uni.setStorageSync(LOCATION_CACHE_KEY, defaultLocation);
      return defaultLocation;
    } catch (boundaryError) {
      // 最后的兜底方案
      const defaultLocation = {
        id: 'default',
        name: '校园内',
        latitude: 39.9042,
        longitude: 116.4074,
        isRealTime: false
      };
      uni.setStorageSync(LOCATION_CACHE_KEY, defaultLocation);
      return defaultLocation;
    }
  }
};

// 获取预设位置列表（保留原有功能）
export const fetchLocationList = async () => {
  try {
    const { data } = await getLocationList();
    return data;
  } catch (error) {
    console.error('获取位置列表失败:', error);
    throw error;
  }
};

// 设置当前位置
export const setCurrentLocation = (location) => {
  uni.setStorageSync(LOCATION_CACHE_KEY, location);
};

// 请求定位权限
export const requestLocationPermission = () => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] === false) {
          // 用户之前拒绝了定位权限，引导用户手动开启
          uni.showModal({
            title: '定位权限',
            content: '需要获取您的位置信息来为您推荐附近商家，请在设置中开启定位权限',
            confirmText: '去设置',
            success: (modalRes) => {
              if (modalRes.confirm) {
                uni.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting['scope.userLocation']) {
                      resolve(true);
                    } else {
                      reject(new Error('用户拒绝开启定位权限'));
                    }
                  }
                });
              } else {
                reject(new Error('用户取消开启定位权限'));
              }
            }
          });
        } else {
          resolve(true);
        }
      }
    });
  });
};

// 使用微信地图选择位置
export const chooseLocationFromMap = () => {
  return new Promise(async (resolve, reject) => {
    try {
      // 先检查定位权限
      await requestLocationPermission();
      
      uni.chooseLocation({
        success: (res) => {
          try {
            console.log('用户选择的位置:', res);
            
            // 直接使用选择的位置，不进行校园范围检查
            const locationData = {
              id: 'map_selected',
              name: res.name || res.address || '地图选择位置',
              latitude: res.latitude,
              longitude: res.longitude,
              address: res.address,
              isRealTime: false,
              isMapSelected: true
            };
            
            // 缓存选择的位置
            setCurrentLocation(locationData);
            resolve(locationData);
            
          } catch (error) {
            console.error('处理选择位置失败:', error);
            reject(error);
          }
        },
        fail: (error) => {
          console.error('选择位置失败:', error);
          if (error.errMsg && error.errMsg.includes('cancel')) {
            reject(new Error('用户取消选择位置'));
          } else {
            reject(new Error('选择位置失败，请重试'));
          }
        }
      });
    } catch (error) {
      console.error('获取定位权限失败:', error);
      reject(error);
    }
  });
};

// 导出校园地理围栏配置获取函数
export { getCampusBoundary };